/*
 * Copyright (c) 2023. li.siyuan All rights reserved.
 */

package com.yanfan.attach.service.impl;

import com.yanfan.attach.domain.SysIdStrategy;
import com.yanfan.attach.mapper.SysIdStrategyMapper;
import com.yanfan.attach.service.ISysIdStrategyService;
import com.yanfan.common.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * @author lisiy
 * @description 针对表【sys_id_strategy(id生成策略表)】的数据库操作Service实现
 * @createDate 2023-02-16 18:50:26
 */
@Service
public class SysIdStrategyServiceImpl implements ISysIdStrategyService {

    @Autowired
    private SysIdStrategyMapper sysIdStrategyMapper;

    @Override
    @Transactional
    public String selectIdByPrefix(String prefix) {
        final SysIdStrategy sysIdStrategy = sysIdStrategyMapper.selectIdStrategyByPrefix(prefix);
        if (Objects.isNull(sysIdStrategy)) {
            throw new ServiceException("编号生成策略不存在: " + prefix);
        }

        final String numberStr = sysIdStrategy.generate();
        // 自增当前ID
        sysIdStrategy.setNumber(sysIdStrategy.formatNumber(Integer.parseInt(sysIdStrategy.getNumber()) + 1));
        int i = updateSysIdStrategy(sysIdStrategy);
        if (i < 0) {
            throw new ServiceException("调整编号生成策略失败: " + prefix);
        }
        return numberStr;
    }

    @Override
    public int updateSysIdStrategy(SysIdStrategy sysIdStrategy) {
        return sysIdStrategyMapper.updateSysIdStrategy(sysIdStrategy);
    }

    @Override
    public int reset() {
        return sysIdStrategyMapper.reset();
    }
}
